// 导入数据库模块
const { db, readDatabase, writeDatabase } = require('./db');
const bcrypt = require('bcrypt');

// 用户模型类
class UserModel {
  // 获取所有用户
  getAllUsers() {
    readDatabase();
    return db.data.users || [];
  }

  // 根据ID获取用户
  getUserById(id) {
    readDatabase();
    return db.data.users.find(user => user.id === id);
  }

  // 根据用户名获取用户
  getUserByUsername(username) {
    readDatabase();
    return db.data.users.find(user => user.username === username);
  }

  // 创建新用户
  async createUser(userData) {
    readDatabase();
    
    // 检查用户名是否已存在
    const existingUser = db.data.users.find(user => user.username === userData.username);
    if (existingUser) {
      throw new Error('用户名已存在');
    }

    // 检查邮箱是否已存在
    if (userData.email) {
      const existingEmail = db.data.users.find(user => user.email === userData.email);
      if (existingEmail) {
        throw new Error('邮箱已被使用');
      }
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(userData.password, 10);

    // 创建新用户对象
    const newUser = {
      id: db.data.users.length > 0 ? Math.max(...db.data.users.map(user => user.id)) + 1 : 1,
      username: userData.username,
      password: hashedPassword,
      email: userData.email || null,
      role: userData.role || 'user',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    // 添加到数据库
    db.data.users.push(newUser);
    writeDatabase();

    // 返回不包含密码的用户信息
    const { password, ...userWithoutPassword } = newUser;
    return userWithoutPassword;
  }

  // 更新用户信息
  async updateUser(id, userData) {
    readDatabase();
    
    const userIndex = db.data.users.findIndex(user => user.id === id);
    if (userIndex === -1) {
      throw new Error('用户不存在');
    }

    const user = db.data.users[userIndex];
    
    // 如果更新了用户名，检查是否已存在
    if (userData.username && userData.username !== user.username) {
      const existingUser = db.data.users.find(u => u.username === userData.username);
      if (existingUser) {
        throw new Error('用户名已存在');
      }
      user.username = userData.username;
    }

    // 如果更新了邮箱，检查是否已存在
    if (userData.email && userData.email !== user.email) {
      const existingEmail = db.data.users.find(u => u.email === userData.email);
      if (existingEmail) {
        throw new Error('邮箱已被使用');
      }
      user.email = userData.email;
    }

    // 如果更新了密码，加密并更新
    if (userData.password) {
      user.password = await bcrypt.hash(userData.password, 10);
    }

    // 更新角色（如果提供）
    if (userData.role) {
      user.role = userData.role;
    }

    // 更新时间戳
    user.updatedAt = new Date().toISOString();

    // 保存更新
    writeDatabase();

    // 返回不包含密码的用户信息
    const { password, ...userWithoutPassword } = user;
    return userWithoutPassword;
  }

  // 删除用户
  deleteUser(id) {
    readDatabase();
    
    const userIndex = db.data.users.findIndex(user => user.id === id);
    if (userIndex === -1) {
      throw new Error('用户不存在');
    }

    // 不允许删除唯一的管理员用户
    const adminUsers = db.data.users.filter(user => user.role === 'admin');
    if (adminUsers.length === 1 && adminUsers[0].id === id) {
      throw new Error('不允许删除唯一的管理员用户');
    }

    // 删除用户
    const deletedUser = db.data.users.splice(userIndex, 1)[0];
    writeDatabase();

    // 返回不包含密码的用户信息
    const { password, ...userWithoutPassword } = deletedUser;
    return userWithoutPassword;
  }

  // 验证用户密码
  async verifyPassword(username, password) {
    const user = this.getUserByUsername(username);
    if (!user) {
      return false;
    }

    const passwordMatch = await bcrypt.compare(password, user.password);
    if (passwordMatch) {
      // 返回不包含密码的用户信息
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    }

    return false;
  }
}

// 导出用户模型实例
module.exports = new UserModel();